

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;


public class getMaps {

    static String genPath = "http://localhost:8090";
    static String genToken = "fiAUVT1Ww8gLKFcJIv73U2sX-9AslphK5_g2aapXfSkHF_IrGQGSh4SGGGQbSL7T3FS8AzQuHDctgvtIogYCwQ..";
//    static String outPutPath = "D:/supermap/iServer/supermap-iserver-1021-22801-6464-windows-x64-deploy-usv3383/supermap-iserver-1021-22801-6464-windows-x64-deploy/webapps/iserver/output/sqlite";

    /**
     * 程序入口点
     * The entrance of the programme.
     */
    public static void main(String[] args) {

        //如果有参数进来，以参数为准
        if (args.length > 0) {
            genPath = args[0];
            genToken = args[1];
        }


        JSONArray jsonArray = getWorkSpaces();
        assert jsonArray != null;

        Map<String, ArrayList<JSONObject>> workSpaceMap = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            // 获取当前索引的JSONObject
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (workSpaceMap.get(jsonObject.get("name")) == null) {
                workSpaceMap.put(jsonObject.get("name").toString(), new ArrayList<>(Arrays.asList(jsonObject)));
            } else {
                workSpaceMap.get(jsonObject.get("name")).add(jsonObject);
            }
        }

//        CloudLicense.login("13198501932", "Lyb123452");

        List<List<String>> data = new ArrayList<>();
        data.add(Arrays.asList("服务名", "地图名"));



        for (Map.Entry<String, ArrayList<JSONObject>> entry : workSpaceMap.entrySet()) {


            ArrayList<JSONObject> list = entry.getValue();

            List<JSONObject> mapServiceList = list.stream().filter(jsonObject -> jsonObject.get("serviceType").toString().equals("MapService")).collect(Collectors.toList());
            if (!mapServiceList.isEmpty()) {

                System.out.println("存在地图服务");
                Map<String, List<JSONObject>> map = mapServiceList.stream()//.map(JSONObject::new)
                        .collect(Collectors.groupingBy(jsonObject -> jsonObject.getString("serviceName").split("/")[0]));
                for (String key : map.keySet()) {
                    System.out.println(key);

                    try {
                        String requestMethod = "GET"; // 请求方式，如 GET 或 POST
                        String url = genPath + "/iserver/services/" + key + "/rest/maps.json";
                        URL apiUrl = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
                        connection.setRequestMethod(requestMethod);
                        connection.setDoOutput(true);

                        //                         读取响应
                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line;
                        StringBuffer response = new StringBuffer();
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        JSONArray ja = JSONArray.parseArray(response.toString());

                        for (int i = 0; i < ja.size(); i++) {
                            System.out.println(ja.getJSONObject(i).getString("name"));
                            data.add(Arrays.asList(key, ja.getJSONObject(i).getString("name")));
                        }

                        connection.disconnect();
                    } catch (IOException e) {
                        System.err.println(e.toString());
                        //throw new RuntimeException(e);
                    }
                }


            }

        }

        try {
            CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("map.csv"), CSVFormat.DEFAULT);
            for (List<String> row : data) {
                csvPrinter.printRecord(row);
            }
            csvPrinter.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


    public static JSONArray getWorkSpaces() {
        try {


            URL url = new URL(genPath + "/iserver/manager/workspaces.json");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + genToken);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            connection.disconnect();
            return JSONArray.parseArray(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}

